<script lang="tsx">
import { defineComponent, ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getLivesApi, getLivesLatestApi, updateLivesViewCountApi, type LivesParams, type LivesResponse } from '#/api/competition/lives';
import { getGroupListApi, type Group } from '#/api/competition/registration-info';
import Banner from './modules/lives/banner.vue';
import AllDynamics from './modules/lives/allDynamics.vue';
import LatestNews from './modules/lives/latest-news.vue';
import { $t } from '#/locales';
import Pagination from './modules/lives/pagination.vue';
export default defineComponent({
  name: 'CompetitionLives',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const loading = ref(false);
    const loadingFlag = ref([false, false, false]);
    const livesData = ref<LivesResponse['data'] | null>(null);
    const currentPage = ref(1);
    const pageSize = ref(5);
    const totalPages = ref(0);
    const groupList = ref<Group[]>([]);
    const currentGroupId = ref<string>('');

    // 查询参数
    const queryParams = ref<LivesParams>({
      compId: route.query.matchId as string,
      groupId: '',
      curPage: 1,
      pageSize: 5,
      module: '1',
      publishStatus: true
    });

    // 模拟左侧全部动态数据
    const allDynamicsData = ref<any[]>([]);

    // 模拟右侧最新动态数据
    const latestDynamicsData = ref<any[]>([]);

    // 获取咨讯数据
    const loadLivesData = () => {
      if (!queryParams.value.compId || !queryParams.value.groupId) {
        return;
      }
      loadingFlag.value[0] = true;
      getLivesApi(queryParams.value).then((response) => {
        if (response && response.data) {
          livesData.value = response.data;
          console.log('咨讯数据:', response.data);
          totalPages.value = Math.ceil(response.pageInfo.totalRows / pageSize.value);
          // 更新左侧全部动态数据
          if (response.data && response.data.length > 0) {
            allDynamicsData.value = response.data.map((item: any) => ({
              id: item.id,
              img: item.img || '/api/placeholder/300/200',
              title: item.subject,
              content: item.intro || item.content,
              date: item.publishTime,
              initialViews: item.initialViews || 0,
              initialVisitors: item.initialVisitors || 0,
              views: item.views || 0,
              visitors: item.visitors || 0
            }));
          } else {
            // 如果API返回空数据，设置为空数组
            allDynamicsData.value = [];
          }
        }
      }).catch((error) => {
        console.error('加载咨讯数据失败:', error);
        allDynamicsData.value = [];
      }).finally(() => {
        loadingFlag.value[0] = false;
      });
    };

    // 切换标签
    const handleTabChange = (groupId: string) => {
      currentGroupId.value = groupId;
      currentPage.value = 1;
      queryParams.value.curPage = 1;
      queryParams.value.groupId = groupId;
      loadLivesData();
      loadLatestNews();
    };

    // 分页处理
    const handlePageChange = (page: number) => {
      currentPage.value = page;
      queryParams.value.curPage = page;
      loadLivesData();
    };

    // 查看文章详情
    const handleViewDetail = (data: any) => {
      try {
        const params = {
          id: data.id
        }
        updateLivesViewCountApi(params).then((res) => {
          console.log('文章详情:', res);
        }).finally(() => {
          console.log('文章详情:', 'finally');
        });
      } catch (error) { }
      router.push({
        path: `competitionLivesDetail/${route.query.matchId}/${currentGroupId.value}/detail/${data.id}`,
      })
    };

    // 获取最新动态数据
    const loadLatestNews = () => {
      if (!route.query.matchId) {
        return;
      }
      loadingFlag.value[1] = true
      getLivesLatestApi({
        compId: route.query.matchId as string,
        curPage: 1,
        pageSize: 5,
        module: '1',
        groupId: currentGroupId.value
      }).then((response) => {
        if (response && response.data && response.data.length > 0) {
          latestDynamicsData.value = response.data.map((item: any) => ({
            id: item.id,
            title: item.subject,
            date: item.publishTime
          }));
          console.log('最新动态数据:', response.data);
        } else {
          latestDynamicsData.value = [];
        }
      }).catch((error) => {
        console.error('加载最新动态失败:', error);
      }).finally(() => {
        loadingFlag.value[1] = false
      })
    };
    // 获取赛事组别列表
    const getGroupList = () => {
      if (!route.query.matchId) {
        return;
      }
      loadingFlag.value[1] = true;
      getGroupListApi({
        compId: route.query.matchId as string,
      }).then((response) => {
        if (response && response.data && response.data.length > 0) {
          groupList.value = response.data;
          // 使用第一个组别的ID
          const firstGroup = response.data[0];
          if (firstGroup) {
            currentGroupId.value = firstGroup.id;
            queryParams.value.groupId = firstGroup.id;

            // 获取到组别数据后，加载咨讯数据
            loadLivesData();
            loadLatestNews();
          }
        }
      }).catch((error) => {
        console.error('获取赛事组别列表失败:', error);
      }).finally(() => {
        loadingFlag.value[1] = false
      })
    };



    onMounted(() => {
      getGroupList();
    });

    watch(loadingFlag, (newVal) => {
      loading.value = newVal.some((item: boolean) => item === true);
    }, { deep: true, immediate: true });

    return () => (
      <div class="competition-lives-container" v-loading={loading.value}>
        {/* Banner区域 */}
        <div class="banner-section">
          <Banner url={''} />
        </div>
        {/* 主要内容区域 */}
        <div class="main-content">
          {/* 赛事组别 */}
          <div class="group-section">
            <h2 class="text-[24px] text-[500] text-[#191919]">{$t('competition.lives.allDynamic')}</h2>
            <div class="text-[14px] text-[#595959] py-[16px]">
              <div class="tab-group">
                {groupList.value.map((item) => (
                  <el-button
                    link
                    plain
                    style={{
                      color: currentGroupId.value === item.id ? '#0067D1' : '#595959'
                    }}
                    onClick={() => handleTabChange(item.id)}
                  >
                    {item.name}
                  </el-button>
                ))}
              </div>
            </div>
          </div>
          <div class="content-wrapper">
            {/* 左侧全部动态 */}
            <AllDynamics allDynamicsData={allDynamicsData.value} handleViewDetail={handleViewDetail} />
            {/* 右侧最新动态 */}
            <div class="right-column">
              <div class="section-header">
                <h2 class="text-[16px] text-[500] text-[#191919]">{$t('competition.lives.latestNews')}</h2>
              </div>
              <LatestNews latestDynamicsData={latestDynamicsData.value} handleViewDetail={handleViewDetail} />
            </div>
          </div>
        </div>

        {/* 分页区域 */}
        {
          totalPages.value > 5 && (
            <Pagination
              totalPages={totalPages.value}
              currentPage={currentPage.value}
              handlePageChange={handlePageChange}
            />
          )
        }

      </div>
    );
  }
})
</script>

<style scoped>
.competition-lives-container {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 主要内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.content-wrapper {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8eaed;
}

.tab-group {
  display: flex;
  gap: 8px;
}

/* 右侧列样式 */
.right-column {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: fit-content;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-wrapper {
    grid-template-columns: 1fr;
    gap: 24px;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 20px;
  }

  .left-column,
  .right-column {
    padding: 20px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>
